import http from "@/http/index.ts"
import {ConveyorPricing, ConveyorPricingListParam, ExportRequest, ExportFieldInfo, ConveyorPricingBatchCopyDto} from '@/api/conveyorPricing/type.ts'

// 新增输送件核价
export const addApi = (data: ConveyorPricing) => {
    return http.post("/conveyorPricing/createConveyorPricing", data)
}

// 分页条件查询列表
export const getListApi = (data: ConveyorPricingListParam) => {
    return http.get("/conveyorPricing/getConveyorPricingList", data)
}

// 编辑输送件核价
export const editApi = (data: ConveyorPricing) => {
    return http.put("/conveyorPricing/updateConveyorPricing", data)
}

// 删除输送件核价
export const deleteApi = (id: number) => {
    return http.delete(`/conveyorPricing/deleteConveyorPricing/${id}`)
}

// 批量删除输送件核价
export const batchDeleteApi = (ids: number[]) => {
    return http.post("/conveyorPricing/batchDelete", { ids })
}

// 新增输送件核价
export const getDetial = (data: ConveyorPricing) => {
    return http.post("/conveyorPricing/getDetial", data)
}

// 导入输送件核价
export const importConveyorPricing = (file: File) => {
    const formData = new FormData()
    formData.append('file', file)
    return http.upload("/conveyorPricing/import", formData)
}

// 导出输送件核价（返回blob）
export const exportConveyorPricing = (searchParam?: Partial<ConveyorPricingListParam>) => {
    let url = `${http['instance'].defaults.baseURL}/conveyorPricing/export`
    
    // 如果有查询参数，则拼接到URL中
    if (searchParam) {
        const params = new URLSearchParams()
        
        // 遍历searchParam的所有属性，添加到URL参数中
        Object.keys(searchParam).forEach(key => {
            const value = (searchParam as any)[key]
            // 过滤掉空值、undefined、null，但保留数字0
            if (value !== undefined && value !== null && value !== '' && value !== 'undefined') {
                params.append(key, String(value))
            }
        })
        
        if (params.toString()) {
            url += `?${params.toString()}`
            console.log('导出URL:', url) // 调试日志
        }
    }
    
    // 创建一个临时的a标签来触发下载
    const link = document.createElement('a')
    link.href = url
    link.style.display = 'none'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    return Promise.resolve()
}

// 自定义字段导出输送件核价
export const exportCustomConveyorPricing = (data: ExportRequest) => {
    console.log('发送自定义导出请求:', data)
    
    // 使用POST请求，需要使用Blob响应类型
    return http.post("/conveyorPricing/exportCustom", data, { responseType: 'blob' }).then(response => {
        console.log('收到导出响应:', response)
        console.log('响应类型:', typeof response)
        console.log('响应是否为Blob:', response instanceof Blob)
        
        // HTTP拦截器对于blob类型返回完整的response对象，需要获取response.data
        let blobData: Blob;
        const responseAny = response as any;
        if (responseAny && typeof responseAny === 'object' && 'data' in responseAny) {
            // 如果是完整的response对象，获取data属性
            blobData = responseAny.data;
        } else if (responseAny && responseAny instanceof Blob) {
            // 如果直接是Blob对象
            blobData = responseAny;
        } else {
            console.error('响应不是预期的格式:', response)
            throw new Error('导出响应格式错误')
        }
        
        // 检查是否是Blob对象
        if (!(blobData instanceof Blob)) {
            console.error('响应数据不是Blob类型:', blobData)
            throw new Error('导出响应格式错误')
        }
        
        // 检查blob大小
        if (blobData.size === 0) {
            throw new Error('导出文件为空')
        }
        
        // 检查是否是错误响应（JSON格式）
        if (blobData.type.includes('application/json') || blobData.type.includes('text/plain')) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader()
                reader.onload = function() {
                    try {
                        const responseText = reader.result as string
                        console.log('错误响应内容:', responseText)
                        
                        // 尝试解析为JSON
                        const errorData = JSON.parse(responseText)
                        reject(new Error(errorData.message || '导出失败'))
                    } catch (parseError) {
                        // 如果不是有效的JSON，直接使用文本内容
                        const responseText = reader.result as string
                        reject(new Error(responseText || '导出失败'))
                    }
                }
                reader.onerror = function() {
                    reject(new Error('读取错误响应失败'))
                }
                reader.readAsText(blobData)
            })
        }
        
        // 验证是否是正确的Excel文件类型
        const validExcelTypes = [
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'application/vnd.ms-excel',
            'application/octet-stream'
        ];
        
        if (!validExcelTypes.some(type => blobData.type.includes(type)) && blobData.type !== '') {
            console.warn('可能不是Excel文件类型:', blobData.type)
        }
        
        // 创建下载链接并触发下载
        const link = document.createElement('a')
        link.href = window.URL.createObjectURL(blobData)
        link.download = `输送件核价数据_${new Date().getTime()}.xlsx`
        link.style.display = 'none'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(link.href)
        
        console.log('自定义导出完成，文件大小:', blobData.size, 'bytes')
        return Promise.resolve()
    }).catch(error => {
        console.error('自定义导出失败:', error)
        throw error
    })
}

// 获取可导出的字段列表
export const getExportFields = () => {
    return http.get("/conveyorPricing/getExportFields")
}

// 下载导入模板（返回blob）
export const downloadTemplate = () => {
    const url = `${http['instance'].defaults.baseURL}/conveyorPricing/downloadTemplate`
    window.location.href = url
    return Promise.resolve()
}

// 更新输送件核价状态
export const updateStatusApi = (params: { id: number, activate: number }) => {
    return http.put("/conveyorPricing/updateStatus", params)
}

// 批量更新输送件核价状态
export const batchUpdateStatusApi = (params: { ids: number[], activate: number }) => {
    return http.put("/conveyorPricing/batchUpdateStatus", params)
}

// 批量复制输送件核价
export const batchCopyApi = (data: ConveyorPricingBatchCopyDto) => {
    return http.post("/conveyorPricing/batchCopy", data)
}